//
//  HMAcceptanceList.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/10/23.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

// 接受列表
class HMAcceptanceList: HMViewController {
     var alJsonData = JSON()
     var alBgImageView = UIImageView()
    // 发布咨询id
     var  consultId = ""
    // 聊天数
    var countNum = 0
    private lazy var  table: UITableView = {
        let _table = UITableView()
        _table.delegate = self
        _table.dataSource = self
        _table.register(HMSessionCell.classForCoder(), forCellReuseIdentifier: "HMSessionCell")
        return _table
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "user/consult/doctor-list", parameters: ["consultId": self.consultId], success: { (json) in
            let code = json["code"]
            if code == 0 {
               self.alJsonData = json["data"]
               self.table.reloadData()
                self.table.isHidden = false
             }else {
                self.table.isHidden = true
               print("----其他失败问题")
             }
        }, fail: { (code, msg) in
            self.showToast(message: msg)
        }) {}
    }
    
    
    override func setupView() {
        self.title = "邀请列表"
        view.backgroundColor = configure.shareConfigure.HMColor2
        
        view.addSubview(alBgImageView)
        view.addSubview(table)
        table.topAlign(view: view, predicate: "0")
        table.leadingAlign(view: view, predicate: "0")
        table.trailingAlign(view: view, predicate: "0")
        table.bottomAlign(view: view, predicate: "0")
        table.isHidden = true
        
        
        alBgImageView.image = UIImage.init(named: "list_null")
        alBgImageView.centerXYAlign(view: view)
        
    }
    
    
}


extension HMAcceptanceList: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return alJsonData.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 88
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = table.dequeueReusableCell(withIdentifier: "HMSessionCell") as! HMSessionCell
        cell.isDoctor = true
        cell.isTitleStr = self.title!
        cell.setJson(json: alJsonData[indexPath.row])
        cell.delegate = self
        return cell
    }
}

extension HMAcceptanceList: HMSessionCellDelegate {
    func sessionCellBtn(sender: UIButton, doctor: Bool) {
      
        
        //用户选择咨询医生
        let doctorIdStr = sender.dictionary!["doctorId"] as! String
        
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.request(url: "user/consult/choose", parameters: ["consultId": self.consultId, "doctorId": doctorIdStr], success: { (json) in
//orderId
            
            let code = json["code"].intValue
            if code == 0 {
                 // 进入支付界面
                let p = HMPayment()
                p.cost = json["data"]["cost"].doubleValue //费用
                p.orderId =  json["data"]["orderId"].stringValue//订单ID
                p.consultId = self.consultId //咨询id
                p.doctorId = doctorIdStr
                self.pushViewController(p)
            }else {
                
            }
//            self.bindingConversation(self.consultId, conversationId, doctorId: doctorIdStr)
        }, fail: { (code, msg) in
            self.showToast(message: msg)
        }) {
        }
        
        
 
//
//
//        // 获取会话
//
//        // 获取当前用户id
//        let currentUserId =  HMPlatform.getCurrentUserId()
//        // 会话ID（通过后台的规则） 对方id +  自己id
//        var conversationId = doctorIdStr + currentUserId
//
//        // 添加好友
//        self.addFriend(id: doctorIdStr)
        // 邀请
//        NetRequestTool.shareInstance.met = .post
//        NetRequestTool.request(url: "user/consult/choose", parameters: ["consultId": self.consultId, "doctorId": doctorIdStr], success: { (json) in
//
//            self.bindingConversation(self.consultId, conversationId, doctorId: doctorIdStr)
//        }, fail: { (code, msg) in
//            self.showToast(message: msg)
//        }) {
//
//            // 获取聊天天数
//            NetRequestTool.shareInstance.met = .get
//            NetRequestTool.request(url: "doctor/consult/chat-count", parameters: ["consultId":self.consultId], success: { (chJson) in
//                self.countNum = chJson["data"]["count"].intValue
//            }, fail: { (chCode, chMsg) in
//                print("doctor/consult/chat-count ==========>",chMsg)
//            }, complete: {
//
//            })
//        }
    }
    
    
    //接口- 绑定聊天会话id
    func bindingConversation(_ consultId: String, _ conversationId: String, doctorId: String) {
        // 绑定聊天会话id ---
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.request(url: "doctor/consult/conversation", parameters: ["consultId": consultId, "conversationId": conversationId], success: { (doJson) in
            
            // 进入聊天
            //                let storyBoard = UIStoryboard(name: "Main", bundle: nil)
            //                let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging
            //                self.pushViewController(_im)
            
            self.addFriend(id: doctorId)
            
        }, fail: { (doCode, doMsg) in
            print("doctor/consult/conversation ==========>",doMsg)
        }, complete: {
            
        })
    }
    
    // 请求添加好友
    func addFriend (id: String) {
        var users = Array<Any>()
        let reg:TIMAddFriendRequest = TIMAddFriendRequest()
        //添加好友
        reg.identifier = String.init(cString: id, encoding: String.Encoding.utf8)
        reg.remark = String.init(cString: "添加备注", encoding: String.Encoding.utf8)
        reg.addWording = String.init(cString: "添加理由", encoding: String.Encoding.utf8)
//        reg.friendGroup = String.init(cString: "医生", encoding: String.Encoding.utf8)
        users.append(reg)

        
        TIMFriendshipManager.sharedInstance()?.addFriend(users, succ: { (ary) in
            for  res  in ary! {
                let fri :TIMFriendResult = res as! TIMFriendResult
                if  fri.status != .FRIEND_STATUS_SUCC  {
//                    print("=====>>>\(fri.identifier, fri.status)")
                    // 发一条消息
                   let con :TIMConversation = HMPlatform.getSomeoneConversation(id)
                   HMElem.foundConversation(con)
                 // 已经是好友
                }else if fri.status == .ADD_FRIEND_STATUS_ALREADY_FRIEND  {
                    let con :TIMConversation = HMPlatform.getSomeoneConversation(id)
                    HMElem.foundConversation(con)
                }else {
                    print("err =====>>>\(fri.identifier, fri.status)")
                }
                
            }
            
            
        }, fail: { (code, err) in
            print("add friend fail: \(code) ===> \(err)")
        })
    }
    
    
    
}
